import React, {memo, useEffect, useState, useRef} from 'react'
import {Button, Space, message, Popconfirm, Tag} from 'antd'
import {PlusOutlined, ArrowDownOutlined} from '@ant-design/icons'
import type {ColumnsType} from 'antd/es/table'
import {history, connect} from 'umi'
import moment from 'moment'
import styles from './index.less'
import SearchForm from '@/components/SearchForm'
import CustomTable from '@/components/Table'

import {
	getTableList,
	deleteInitiation,
	applycostImport,
	getSupplierBaseExcelList,
	auditFlow,
	getIsProcessOpen,
} from '@/service/purchase/initiation'
import {getDict} from '@/service/common/dict'
import {getUseList} from '@/service/system/user'
import Permissions from '@/components/Permissions'
import {formatDate} from '@/utils/common/dateFilter'
import 'moment/locale/zh-cn'
import BatchUpload from '@/components/BatchUpload'
import {modalApi} from '@/utils/modalReq'
import {downloadDocumentUrl} from '@/service/common/download'
import {auditStatus} from '../dict'
import {processRecordSave} from '@/service/common'

const formItemLayout = {
	labelCol: {flex: '100px'},
	wrapperCol: {flex: '1'},
}
interface DataType {
	projectName: string
	principalName: string
	costsNames: string
	resultMsg: string
}

const initiation = memo(
	(props: {
		user: {
			userId: string
			orgId: string | number
			userName: string
		}
	}) => {
		const {userId, orgId, userName} = props.user
		const [params, setParams] = useState({
			current: 1,
			size: 10,
		})
		const [total, setTotal] = useState()
		const [loading, setLoading] = useState(false)
		// 项目申请人
		const [userList, setApplyUser] = useState<any[]>([])
		const [dict, setDict] = useState({
			purchase_costs_type: [],
		})
		const [tableList, setTableList] = useState<any[]>([])
		const [searchData, setSearchData] = useState<any>()
		const [formData, setFormData] = useState<any[]>([])
		const [isUploadModalOpen, setIsUploadModalOpen] = useState(false)
		const [processOpen, setProcessOpen] = useState<number>(0)
		// 初始化-流程是否激活
		const getIsProcessOpenFun = () => {
			getIsProcessOpen({businessType: 1})
				.then((res: any) => {
					if (res?.success) {
						setProcessOpen(() => res?.data)
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}
		// 获取表格数据
		const onListFun = () => {
			setLoading(true)
			getTableList({...params, ...searchData})
				.then((res: any) => {
					if (res?.data?.records) {
						setTableList(() => res?.data?.records)
						setTotal(res?.data?.total)
						setLoading(false)
					}
				})
				.catch(() => {
					setLoading(false)
				})
		}
		// 初始化-项目申请人
		const getApplyUser = () => {
			getUseList({merchantId: orgId}).then((res: any) => {
				if (res?.success) {
					setApplyUser(() => res.data)
				}
			})
		}
		useEffect(() => {
			getApplyUser()
		}, [orgId])

		useEffect(() => {
			// 初始化
			getDict(
				{
					dictKeys: ['purchase_costs_type'],
				},
				(res: any) => {
					setDict(res)
				},
			)
			getIsProcessOpenFun()
		}, [])

		useEffect(() => {
			const formItems: any[] = [
				{
					type: 'group',
					key: 'group1',
					groupItems: [
						{
							type: 'input',
							label: '立项编号',
							name: 'projectNo',
							key: 'projectNo',
						},
						{
							type: 'input',
							label: '项目名称',
							name: 'projectName',
							key: 'projectName',
						},
						{
							type: 'input',
							label: '项目负责人',
							name: 'principalName',
							key: 'principalName',
						},
					],
				},
				{
					type: 'group',
					key: 'group2',
					groupItems: [
						{
							type: 'dateRange',
							key: 'applyTime',
							name: 'applyTime',
							label: '申请日期',
						},
						{
							type: 'select',
							key: 'costsTypes',
							name: 'costsTypes',
							label: '费用类型',
							showSearch: true,
							keys: 'dictKey',
							title: 'dictValue',
							items: [...dict.purchase_costs_type],
						},
						{
							type: 'rangeInput',
							label: '项目预算范围',
							name: 'budget',
							list: ['budgetMix', 'budgetMax'],
							key: 'budget',
							text: '至',
						},
					],
				},
				{
					type: 'group',
					key: 'group3',
					groupItems: [
						{
							type: 'select',
							label: '立项申请人',
							name: 'applyUserid',
							key: 'applyUserid',
							keys: 'id',
							showSearch: true,
							title: 'name',
							items: [...userList],
						},
						{
							type: 'select',
							key: 'auditStatus',
							name: 'auditStatus',
							label: '审核状态',
							keys: 'key',
							title: 'label',
							items: [...auditStatus],
						},
						{},
					],
				},
			]
			setFormData(formItems)
		}, [dict, userList])

		// 获取表格数据
		// 自定义一个初始不更新的hook
		const useUpdateEffect = (fn: Function, inputs: any[]) => {
			const didMountRef = useRef(false)
			useEffect(() => {
				if (didMountRef.current) fn()
				else didMountRef.current = true
			}, inputs)
		}

		// 使用自定义hook
		useUpdateEffect(onListFun, [params])

		// 导出事件
		const onExportClick = () => {
			downloadDocumentUrl({
				resourceId: '141',
				queryDesc:
					'projectNo:立项编号,projectName:项目名称,principalName:项目负责人,costsTypes:费用类型,budgetMix:项目预算范围最小值,budgetMax:项目预算范围最大值,applyUserid:立项申请人Id,auditStatus:审核状态,applyTimeStart:申请日期（开始时间：yyyy-MM-dd）,applyTimeEnd:申请日期（结束时间：yyyy-MM-dd）',
				queryParam: searchData,
			})
		}
		// 删除事件
		const onDeleteFun = (ids: string) => {
			deleteInitiation({ids})
				.then((res: {msg: string; success: boolean}) => {
					if (res?.success) {
						message.success(res.msg)
						onListFun()
					}
				})
				.catch((err) => {
					message.error(err)
				})
		}

		// 流程作废
		const onAuditFlowFun = (record: {id: string; instanceId: string}) => {
			auditFlow({
				businessId: record?.id,
				instanceId: record?.instanceId,
				message: JSON.stringify({
					type: 'self',
					message: '已作废',
					userName,
					userId,
				}),
				pass: '3',
			})
				.then((res: {msg: string; success: boolean}) => {
					if (res?.success) {
						processRecordSave({
							bizType: 1,
							bizNo: record?.id,
							processId: record?.instanceId,
						})
						message.success(res.msg)
						onListFun()
					}
				})
				.catch((err: any) => {
					message.error(err)
				})
		}

		const columns: ColumnsType<InitiationAPI.InitiationColumns> = [
			{
				title: '序号',
				dataIndex: 'order',
				align: 'center',
				width: 70,
				render(text, record, index) {
					return <span>{(params.current - 1) * 10 + index + 1}</span>
				},
			},
			{
				title: '项目编号',
				dataIndex: 'projectNo',
				width: 200,
				align: 'center',
				ellipsis: true,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '审核状态',
				dataIndex: 'auditStatus',
				align: 'center',
				width: 100,
				render: (text: number, record: any) => (
					<>
						{auditStatus?.map(
							(item: {key: number; label: string}) => {
								if (item?.key === Number(text)) {
									return (
										<Tag
											color="processing"
											key={record?.id}>
											{item?.label}
										</Tag>
									)
								}
								return ''
							},
						)}
					</>
				),
			},
			{
				title: '项目名称',
				dataIndex: 'projectName',
				width: 160,
				align: 'center',
				ellipsis: true,
				render: (text: string) => (
					<div className="ellipsis" style={{width: 140}}>
						{text || '--'}
					</div>
				),
			},
			{
				title: '项目负责人',
				dataIndex: 'principalName',
				align: 'center',
				width: 150,
				ellipsis: true,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目开始日期',
				dataIndex: 'startTime',
				align: 'center',
				width: 180,
				ellipsis: true,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '项目结束日期',
				dataIndex: 'finishTime',
				align: 'center',
				width: 180,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '费用类型',
				dataIndex: 'costsTypes',
				align: 'center',
				width: 100,
				render: (text: number, record: any) => (
					<>
						{dict?.purchase_costs_type?.map(
							(item: {dictKey: number; dictValue: string}) => {
								if (Number(item?.dictKey) === Number(text)) {
									return (
										<Tag
											color="processing"
											key={record?.id}>
											{item?.dictValue}
										</Tag>
									)
								}
								return ''
							},
						)}
					</>
				),
			},
			{
				title: '预算金额',
				dataIndex: 'budget',
				align: 'center',
				width: 200,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '剩余预算金额',
				dataIndex: 'budgetSurplus',
				align: 'center',
				width: 180,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '城市',
				dataIndex: 'applyCityname',
				align: 'center',
				width: 100,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '申请人',
				dataIndex: 'applicantName',
				align: 'center',
				width: 150,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '申请日期',
				dataIndex: 'applyTime',
				align: 'center',
				width: 180,
				render: (text) => (
					<span>
						{' '}
						{processOpen === 1
							? moment(text).format('YYYY-MM-DD HH:mm:ss')
							: moment(text).format('YYYY-MM-DD')}
					</span>
				),
			},
			{
				title: '操作',
				key: 'action',
				align: 'center',
				fixed: 'right',
				width: 250,
				render: (text: any, record: any) => (
					<div>
						<Permissions permissionID="amc_assetCenter_purchase_initiation_view">
							<Button
								type="link"
								size="small"
								onClick={() => {
									history.push({
										pathname: '/purchase/initiation/view',
										query: {
											id: record.id,
										},
									})
								}}>
								详情
							</Button>
						</Permissions>
						{record?.isAudit === 1 &&
						record?.auditStatus !== '4' ? (
							<Permissions permissionID="amc_assetCenter_purchase_initiation_process">
								<Button
									type="link"
									size="small"
									onClick={() => {
										history.push({
											pathname:
												'/purchase/initiation/process',
											query: {
												id: record.id,
											},
										})
									}}>
									审核
								</Button>
							</Permissions>
						) : null}
						{String(record?.createUser) === String(userId) ? (
							<>
								{record?.auditStatus === '3' ? (
									<Permissions permissionID="amc_assetCenter_purchase_initiation_cancel">
										<Popconfirm
											placement="topLeft"
											title="你确定要作废这条数据吗？"
											onConfirm={() =>
												onAuditFlowFun(record)
											}
											okText="确定"
											cancelText="取消">
											<Button type="link" size="small">
												作废
											</Button>
										</Popconfirm>
									</Permissions>
								) : (
									<></>
								)}
								{record?.auditStatus === '9' ? (
									<>
										<Permissions permissionID="amc_assetCenter_purchase_initiation_edit">
											<Button
												type="link"
												size="small"
												onClick={() => {
													history.push({
														pathname:
															'/purchase/initiation/edit',
														query: {
															id: record.id,
														},
													})
												}}>
												编辑
											</Button>
										</Permissions>
									</>
								) : null}
								{record?.auditStatus === '4' ? (
									<>
										<Permissions permissionID="amc_assetCenter_purchase_initiation_reissue">
											<Button
												type="link"
												size="small"
												onClick={() => {
													history.push({
														pathname:
															'/purchase/initiation/edit',
														query: {
															id: record.id,
														},
													})
												}}>
												再次发起
											</Button>
										</Permissions>
									</>
								) : null}
								{record?.auditStatus === '9' ||
								record?.auditStatus === '4' ? (
									<Permissions permissionID="amc_assetCenter_purchase_initiation_delete">
										<Popconfirm
											placement="topLeft"
											title="你确定要删除这条数据吗？"
											onConfirm={() =>
												onDeleteFun(record.id)
											}
											okText="确定"
											cancelText="取消">
											<Button type="link" size="small">
												删除
											</Button>
										</Popconfirm>
									</Permissions>
								) : null}
							</>
						) : null}
					</div>
				),
			},
		]
		// 初始化分页
		useEffect(() => {
			const param = {
				current: 1,
				size: 10,
			}
			setParams(() => param)
		}, [searchData])
		// 搜索
		const onFinish = (values: any) => {
			const applyTimeStart = formatDate(
				values?.applyTime?.[0],
				'YYYY-MM-DD',
			)
			const applyTimeEnd = formatDate(
				values?.applyTime?.[1],
				'YYYY-MM-DD',
			)
			const search = {
				...values,
				budgetMix: values?.budgetMix,
				budgetMax: values?.budgetMax,
				applyTimeStart,
				applyTimeEnd,
			}
			delete search?.applyTime
			setSearchData(() => search)
		}

		// 搜索重置
		const onReset = () => {
			setSearchData({})
		}

		const errorColumns: ColumnsType<DataType> = [
			{
				title: '项目名称',
				dataIndex: 'projectName',
				align: 'center',
				width: 160,
				render: (text: string) => (
					<div className="ellipsis" style={{width: 140}}>
						{text || '--'}
					</div>
				),
			},
			{
				title: '项目申请人',
				dataIndex: 'applyUsername',
				align: 'center',
				width: 140,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '费用类型',
				dataIndex: 'costsNames',
				align: 'center',
				width: 140,
				render: (text: string) => <span>{text || '--'}</span>,
			},
			{
				title: '失败原因',
				dataIndex: 'resultMsg',
				align: 'center',
				width: 140,
				render: (text: string) => <span>{text || '--'}</span>,
			},
		]

		return (
			<div className={styles.page}>
				<div className="search">
					{formData && (
						<SearchForm
							onFinish={onFinish}
							onReset={onReset}
							formItems={formData}
							formLayout={formItemLayout}
						/>
					)}
				</div>
				<div className="btnlist">
					<Space size={12}>
						<Permissions permissionID="amc_assetCenter_purchase_initiation_add">
							<Button
								icon={<PlusOutlined />}
								type="primary"
								ghost
								size="small"
								onClick={() => {
									history.push('/purchase/initiation/add')
								}}>
								新增
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_purchase_initiation_import">
							<Button
								icon={<ArrowDownOutlined />}
								ghost
								size="small"
								className="btn_import"
								onClick={() => setIsUploadModalOpen(true)}>
								导入
							</Button>
						</Permissions>
						<Permissions permissionID="amc_assetCenter_purchase_initiation_export">
							<Button
								icon={<ArrowDownOutlined />}
								ghost
								size="small"
								className="btn_warning"
								onClick={onExportClick}>
								导出
							</Button>
						</Permissions>
					</Space>
				</div>
				<div className="table">
					<CustomTable
						kid="id"
						params={params}
						columns={columns}
						total={total}
						scroll={{y: 480}}
						pagination
						callback={(pagination: any) => {
							setParams(pagination)
						}}
						loading={loading}
						dataSource={tableList}
					/>
				</div>
				<BatchUpload
					isModalOpen={isUploadModalOpen}
					setIsModalOpen={setIsUploadModalOpen}
					importData={applycostImport}
					onTableList={getSupplierBaseExcelList}
					getListData={onListFun}
					fileNmae="file"
					uploadFileUrl={`${modalApi.purchase}/shopec-purchase-applycost/applycost/import/view`}
					columns={errorColumns}
					sourceId={16}
					templateType="费用立项"
				/>
			</div>
		)
	},
)
export default connect(({user}: any) => ({user}))(initiation)
